package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.MeterBrandDAO;
import mwa.cs.dao.MeterSizeDAO;
import mwa.cs.dao.ReaderDAO;
import mwa.cs.dao.ReceiveCodeDAO;
import mwa.cs.dao.RequestTypeDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.MeterSize;
import mwa.cs.model.RequestQuote;
import mwa.cs.util.JDate;
/**
 * Servlet implementation class CS11007Srvl
 */
public class CS11007Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private Database db;
	private String vaUrlAddress;
	private String vaAgentBrowser;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS11007Srvl() {
        super();
       
    }
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		String vaProcessType = request.getParameter("process_type");
    	
		if(vaProcessType.equals("insert")){ 
			 insert(request,response);	
		} else if(vaProcessType.equals("edit")){ 
			edit(request , response);
		}else if(vaProcessType.equals("delete")){
			delete(request,response);
		}else if(vaProcessType.equals("update")) {
			update(request,response);
		}else if(vaProcessType.equals("getDataTable")){
			getDataTable(request,response);
		}else if (vaProcessType.equals("getOperate")){
			getOperate(request,response);
		}else if  (vaProcessType.equals("getReceiveCode")){
			getReceiveCode(request,response);
		}else{
			getDataFromReceiveDataTable(request,response);
		}
    }
    
    public void delete(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db  = new Database();
		String vaMeterCode = request.getParameter("meterCode");
		String vaOperte = request.getParameter("requestType");
		MeterSizeDAO voSizeDAO = new MeterSizeDAO(db);
		try {
			db.beginTransaction();
			voSizeDAO.deleteReceiveCodeANDFee(vnSiteId, vaOperte,vaMeterCode);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11007", JDate.getDate(), JDate.getTime(),vnUserId, "CS11007Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		}

		this.db.close();
		response.getWriter().write("success");
		
   }

    
    @SuppressWarnings("unchecked")
	public void edit(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db  = new Database();
		String vaRequestType = request.getParameter("requestType");
		String vaMeterCode = request.getParameter("meterCode");
		
		JSONObject voObject = new JSONObject();
		PrintWriter voOut = response.getWriter();
		MeterSizeDAO voSizeDAO = new MeterSizeDAO(db);
		List<Map<String, Object>> voResult = voSizeDAO.getReceiveCodeAndFee(vnSiteId,vaRequestType,vaMeterCode);
		String[] voReceiveCode = new String[voResult.size()];
		String[] voReceiveAmount = new String[voResult.size()];
		for (int i = 0; i < voResult.size(); i++) {
			Map<String, Object> voMap = voResult.get(i);
			voReceiveCode[i] = voMap.get("RECEIVE_CODE").toString();
			voReceiveAmount[i] = voMap.get("FEE").toString();
		}
		JSONArray voListReceiveCode = new JSONArray();
		if (voReceiveCode != null) {
			for (int i = 0; i < voReceiveCode.length; i++) {
				voListReceiveCode.add(voReceiveCode[i]);
			}
		}
		JSONArray voListReceiveAmount = new JSONArray();
		if (voReceiveAmount != null) {
			for (int i = 0; i < voReceiveAmount.length; i++) {
				voListReceiveAmount.add(voReceiveAmount[i]);
			}
		}
		
		voObject.put("receiveLength",voReceiveCode.length);
		voObject.put("receive_code", voListReceiveCode);
		voObject.put("receive_amount", voListReceiveAmount);
		
		this.db.close();
		voOut.print(voObject.toJSONString());
		
    }
    
    public void insert(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db  = new Database();
		String vaOperte = request.getParameter("operate");
		String vaMeterCode = (String) request.getParameter("meterCode");
		String vaMeterSize = (String) request.getParameter("meterSize");
		String vaMeterFee = (String) request.getParameter("meterService");
		String voReceiveCode[] = request.getParameterValues("receive_code[]");
		String voReceiveAmount[]= request.getParameterValues("receive_amount[]");
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		
		//System.out.println(vaMeterCode+"   "+vaMeterSize+"   "+vaMeterFee);
		for(int i=0;i<voReceiveCode.length;i++){
			for(int j=0;j<voReceiveCode.length;j++){
				if(voReceiveCode[i] != null && !voReceiveCode[i].equals("") && (voReceiveCode[i].equals(voReceiveCode[j])) && i != j){
					/*System.out.println("รวมค่า");*/
					voReceiveAmount[i] = ""+ (Double.parseDouble(voReceiveAmount[i]) + Double.parseDouble(voReceiveAmount[j]));
					voReceiveCode[j] = null ;
					voReceiveAmount[j] = "0";
				}
			 }
		}
		//insert in database
		
		MeterSizeDAO voSizeDAO = new MeterSizeDAO(db);
		String varRequestType = voSizeDAO.checkRequestType(vnSiteId, vaOperte, vaMeterCode);
		if(varRequestType == null){
			for(int i=0;i<voReceiveCode.length;i++){
				if(voReceiveCode[i] != null && !voReceiveAmount[i].equals("0") && !voReceiveAmount[i].equals("")){
					String vaReceiveCode = voReceiveCode[i];
					double vnReceiveAmount = Double.parseDouble(voReceiveAmount[i]);
					
					//System.out.println(vaReceiveCode);
					MeterSize poMeterSize = new MeterSize();
					poMeterSize.setVnSiteId(vnSiteId);
					poMeterSize.setVaMeterSizeCode(vaMeterCode);
					poMeterSize.setVaRequestType(vaOperte);
					poMeterSize.setVaReceiveCode(vaReceiveCode);
					poMeterSize.setVaDescription(vaMeterSize);
					poMeterSize.setVnFee(vnReceiveAmount);
					poMeterSize.setVnInsertUserId(vnUserId);
					poMeterSize.setVaInsertDate(vaDate);
					poMeterSize.setVaInsertTime(vaTime);
					
				//	MeterSizeDAO daoSizeDAO = new MeterSizeDAO(db);
					try {
						db.beginTransaction();
						voSizeDAO.addMeterSize(poMeterSize);
						db.commit();
					} catch (Exception e) {
						SMErrorLogDAO.getInstance().addLog(0, "CS11007", JDate.getDate(), JDate.getTime(),vnUserId, "CS11007Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
						db.rollback();
						e.getMessage();
					} finally {
						this.db.close();
					}
					response.getWriter().write("success");
					
				}
				}
			this.db.close();
			response.getWriter().write("is emtry");
		}else{
			this.db.close();
			response.getWriter().write("have_requestType");
		}
    }
    
    public void update(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db  = new Database();
		String vaOperte = request.getParameter("operate");
		String vaMeterCode = (String) request.getParameter("meterCode");
		String vaMeterSize = (String) request.getParameter("meterSize");
		String vaMeterFee =  (String) request.getParameter("meterService");
		
		String voReceiveCode[] = request.getParameterValues("receive_code[]");
		String voReceiveAmount[]= request.getParameterValues("receive_amount[]");
		
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		
		for(int i=0;i<voReceiveCode.length;i++){
			for(int j=0;j<voReceiveCode.length;j++){
				if(voReceiveCode[i] != null && !voReceiveCode[i].equals("") && (voReceiveCode[i].equals(voReceiveCode[j])) && i != j){
					voReceiveAmount[i] = ""+ (Double.parseDouble(voReceiveAmount[i]) + Double.parseDouble(voReceiveAmount[j]));
					voReceiveCode[j] = null ;
					voReceiveAmount[j] = "0";
				}
			}
		}
		
		MeterSizeDAO voSizeDAO = new MeterSizeDAO(db);
		
		try {
			db.beginTransaction();
			voSizeDAO.deleteReceiveCodeANDFee(vnSiteId, vaOperte,vaMeterCode);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11007", JDate.getDate(), JDate.getTime(),vnUserId, "CS11007Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		} finally {
			this.db.close();
		}
		
		for(int i=0;i<voReceiveCode.length;i++){
			if(voReceiveCode[i] != null && !voReceiveAmount[i].equals("0") && !voReceiveAmount[i].equals("")){
				String vaReceiveCode = voReceiveCode[i];
				double vnReceiveAmount = Double.parseDouble(voReceiveAmount[i]);
				
				MeterSize poMeterSize = new MeterSize();
				poMeterSize.setVnSiteId(vnSiteId);
				poMeterSize.setVaMeterSizeCode(vaMeterCode);
				poMeterSize.setVaRequestType(vaOperte);
				poMeterSize.setVaReceiveCode(vaReceiveCode);
				poMeterSize.setVaDescription(vaMeterSize);
				poMeterSize.setVnFee(vnReceiveAmount);
				poMeterSize.setVnUpdateUserId(vnUserId);
				poMeterSize.setVaUpdateDate(vaDate);
				poMeterSize.setVaUpdateTime(vaTime);
				
				try {
					db.beginTransaction();
					voSizeDAO.addMeterSize(poMeterSize);
					db.commit();
				} catch (Exception e) {
					SMErrorLogDAO.getInstance().addLog(0, "CS11007", JDate.getDate(), JDate.getTime(),vnUserId, "CS11007Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
					db.rollback();
					e.getMessage();
				}finally{
					this.db.close();
				}
				response.getWriter().write("success_update");
			}
		}

    }			
    
    public void getDataFromReceiveDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	String vaCode = request.getParameter("vaCode");
		String vaSize = request.getParameter("vaSize");
		String vaFee = request.getParameter("vaFee");
		request.setAttribute("MeterCode",vaCode);
		request.setAttribute("MeterSize", vaSize);
		request.setAttribute("MeterService",vaFee);
		RequestDispatcher voRequestDispatcher = request.getRequestDispatcher("CS11007.jsp");
		voRequestDispatcher.forward(request, response);
    }
    
    @SuppressWarnings("unchecked")
	public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		JSONArray voRequestType = new JSONArray();
		JSONArray voReceiveCode = new JSONArray();
		JSONArray voFee = new JSONArray();
		PrintWriter voOut = response.getWriter();
		String vaMeterCode = (String) request.getParameter("meterCode");
		this.db = new Database();
		//MeterBrandDAO daoBrandDAO = new MeterBrandDAO(db);
		MeterSizeDAO voSizeDAO = new MeterSizeDAO(db);
		List<Map<String , Object>> voListFindAll;
		List<Map<String , Object>> voListReuest;
		
		voListFindAll = voSizeDAO.getAllMeterSizeBySiteId(vnSiteId,vaMeterCode);
		int vnSeq =0;
		String vaPrevious = "";
		DecimalFormat voFormatter = new DecimalFormat("#,###,###.00");
		for(int i = 0; i < voListFindAll.size() ; i++){ 
			Map<String , Object> mapItem = (Map<String , Object>) voListFindAll.get(i);
			voColumn = new JSONArray();
			
			if(!vaPrevious.equals(mapItem.get("REQUEST_TYPE").toString()+" "+mapItem.get("REQUEST_DESCRIPTION").toString())){
				
				voReceiveCode = new JSONArray();
				voFee = new JSONArray();
				vnSeq ++;
				voColumn.add(vnSeq);
				voColumn.add(mapItem.get("REQUEST_TYPE")+" "+mapItem.get("REQUEST_DESCRIPTION"));
				voListReuest  = voSizeDAO.findDescriptionInReceiveCodeByRequestTypeAndMeterSize(vnSiteId, mapItem.get("REQUEST_TYPE").toString(), vaMeterCode);
				for(int j=0;j<voListReuest.size();j++){
					Map<String , Object> map= (Map<String , Object>) voListReuest.get(j);
					voReceiveCode.add(map.get("RECEIVE_CODE")+" "+map.get("DESCRIPTION"));
					voFee.add(voFormatter.format(Double.parseDouble(map.get("FEE").toString())));
				}
				voColumn.add(voReceiveCode);
				voColumn.add(voFee);
				voColumn.add(mapItem.get("REQUEST_TYPE")+" "+mapItem.get("REQUEST_DESCRIPTION"));
				voColumn.add(mapItem.get("REQUEST_TYPE"));
				voColumn.add(mapItem.get("RECEIVE_CODE"));
				voRow.add(voColumn);
				
			}else{
				
			}
			vaPrevious = mapItem.get("REQUEST_TYPE").toString()+" "+mapItem.get("REQUEST_DESCRIPTION").toString();
		}
		
		voObject.put("aaData", voRow);
		
		this.db.close();
		voOut.print(voObject.toJSONString());
		
    }
    
    
    @SuppressWarnings("unchecked")
	public void getReceiveCode(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	this.db = new Database();
		PrintWriter voOut = response.getWriter();
		String[] vaMessage = null, vaValue = null;
		ReceiveCodeDAO voReceiveCodeDAO = new ReceiveCodeDAO(db);
		String vaCondition = "receive_code != 21 AND receive_code != 22 ORDER BY receive_code ASC";
		List<Map<String, Object>> voResult = voReceiveCodeDAO.findReceiveCodeByCondition(vnSiteId, vaCondition);

		vaValue = new String[voResult.size()];
		vaMessage = new String[voResult.size()];
		
		for (int i = 0; i < voResult.size(); i++) {
			Map<String, Object> voObject = voResult.get(i);
			vaValue[i] = voObject.get("RECEIVE_CODE").toString();
			vaMessage[i] = voObject.get("RECEIVE_CODE")+" "+voObject.get("DESCRIPTION");
		}
		
		JSONObject voObject = new JSONObject();
		JSONArray voListMessages = new JSONArray();
		if (vaMessage != null) {
			for (int i = 0; i < vaMessage.length; i++) {
				voListMessages.add(vaMessage[i]);
			}
		}
		voObject.put("messages", voListMessages);
		JSONArray voListValues = new JSONArray();
		if (vaValue != null) {
			for (int i = 0; i < vaValue.length; i++) {
				voListValues.add(vaValue[i]);
			}
		}
		voObject.put("values", voListValues);
		
		this.db.close();
		voOut.print(voObject.toJSONString());	
    }

    public void getOperate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db  = new Database();
		String[] vaReadName = null, vaReadId = null;
		this.db = new Database();
		
			RequestTypeDAO voRequestTypeDAO = new RequestTypeDAO(db);
			List<Map<String,Object>>  voResult = voRequestTypeDAO.findRequestTypeBySiteId(vnSiteId);
			vaReadName = new String[voResult.size()];
			vaReadId = new String[voResult.size()];
			for(int i=0;i<voResult.size();i++){
				Map<String,Object> voObject = voResult.get(i);
				vaReadName[i] = voObject.get("REQUEST_TYPE")+" "+voObject.get("REQUEST_DESCRIPTION").toString();
				vaReadId[i] =  voObject.get("REQUEST_TYPE").toString();
			}
			
			JSONObject voObject = new JSONObject();
			JSONArray voList = new JSONArray();
			PrintWriter voOut = response.getWriter();
			if (vaReadName != null) {
				for (int i = 0; i < vaReadName.length; i ++) {
					voList.add(vaReadName[i]);
				}
			}
			voObject.put("readName", voList);
			JSONArray voList2 = new JSONArray();
			if (vaReadId != null) {
				for (int i = 0; i < vaReadId.length; i ++) {
					voList2.add(vaReadId[i]);
				}
			}
			voObject.put("readId", voList2);
			
			this.db.close();
			voOut.print(voObject.toJSONString());
			
    }
    		
    	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

}
